
from openpyxl import load_workbook


class Excel:
    def __init__(self, path, sheetname):
        self.path = load_workbook(path)
        self.sheetname = self.path[sheetname]

    def get_data(self):
        datalist = []
        # 获取第一行作为标题行
        headers = [cell.value for cell in next(self.sheetname.rows)]

        # 重置迭代器，因为上面已经消耗了一行
        self.sheetname.reset()
        next(self.sheetname.rows)  # 跳过标题行

        for row in self.sheetname:
            row_data = {}
            for idx, cell in enumerate(row):
                # 只有当对应的标题不为空时才添加该列
                if idx < len(headers) and headers[idx] is not None:
                    row_data[headers[idx]] = cell.value
            datalist.append(row_data)

        return datalist